
#include "tmpbuf.h"

int tmpbuf_init(tmpbuf_t *buf, size_t cap)
{
    if (buf == NULL)
        return -1;
    buf->cap = TMPBUF_MAX;
    memset(buf->tmp, 0, buf->cap);
    buf->buf = buf->tmp;

    if (cap > TMPBUF_MAX)
    {
        char *tmpbuf = (char *)malloc(cap);
        if (tmpbuf != NULL)
        {
            buf->cap = cap;
            buf->buf = tmpbuf;
            memset(buf->buf, 0, buf->cap);
        }
        else
        {
            return -2;
        }
    }
    return 0;
}

void tmpbuf_deinit(tmpbuf_t *buf)
{
    if (buf == NULL)
        return;
    if (buf->buf != buf->tmp && buf->cap > TMPBUF_MAX)
    {
        free(buf->buf);
        buf->cap = TMPBUF_MAX;
        buf->buf = buf->tmp;
    }
}